package com.pss.gateway.component;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 鉴权管理器，用于判断是否有资源的访问权限
 */
@Component
@Slf4j
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        //从Redis中获取当前路径可访问角色列表
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();

        String token = request.getHeaders().getFirst("Authorization");
        // 如果token为空 或 不是以"bearer "为前缀 则无效并且需要鉴权
        if (StringUtils.isEmpty(token) || !token.startsWith("bearer ")) {
//            log.info("token为空 或 不是以 bearer 为前缀 则无效并且需要鉴权");
            return Mono.just(new AuthorizationDecision(false));
        }

        URI uri = request.getURI();
        Object obj = redisTemplate.opsForValue().get("RESOURCE_ROLES_MAP");
        Map<String, List<String>> apiRoleMap = (Map<String, List<String>>) obj;

        String path = uri.getPath();
        List<String> authorities = apiRoleMap.get(path);
        if (CollectionUtils.isEmpty(authorities)){
            return Mono.just(new AuthorizationDecision(true));
        }
        //认证通过且角色匹配的用户可访问当前路径
        List<String> finalAuthorities = authorities;
        return mono
                .filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                .any(auth -> finalAuthorities.contains(auth))
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

}
